// pages/select/select.js
var util = require('../../utils/util.js')
var scrolldistance = 0
var heightArr2 = undefined
var tempCartList = []
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showLoading: false, //加载动画
    showDeliveryCostIns: false, // 显示运费规则声明
    clickTimes: 0, //去结算按钮点击次数 --临时变量，不与视图层交互
    buyCount: 0, //购物车总数量
    allPrice: 0, //购物车总价
    allDiscount: 0, //购物车总折扣
    yoghourt: null, //酸奶产品数据
    scrollId: null, //scroll-into-view值 
    navActiveId: 0, //导航栏激活id
    showDetail: false, //是否显示商品详情
    detailInfo: undefined, //商品详情信息
    optionData: undefined, //商品选项区域数据
    optionRemark: '', //商品选项上方说明区域内容
    showOption: false, //显示商品选择窗体 
    initialPrice: 0, //选项列表中的产品初始价格
    optionDescrib: '', //已选加料说明
    currentPrice: 0, //选项列表中的实时价格
    cartListData: [], //购物车列表数据
    currentAdditions: [], //当前选项界面所选小料列表
    currentDiscount: 0, //当前所选产品的优惠价格
    showCartInfo: false, //显示购物车信息
    scrollType: '点击导航', //定义滚动类型,
    promotionList: undefined, //优惠产品列表
    showPromotionList: false, //控制显示：优惠产品列表
    optionFormScrollTop: 0, //选项窗口中的滚动条位置
    //--------------------------配送费信息参数
    deliveryCost: 0, //配送费实际值
    deliveryCostReduce: 0, //配送费减免额度
    needBuyMore: 0, // 需要多买多少钱免配送费
    deliveryCostTips: [], //配送费信息说明
    extraDeliveryCost: 0 //超出配送时间段的每单加价
  },
  //-----------【配送费说明:隐藏】
  deliveryCostInsHide: function () {
    this.setData({
      showDeliveryCostIns: false
    })
  },
  //-----------【配送费说明:显示】
  deliveryCostInsShow: function () {
    this.setData({
      showDeliveryCostIns: true
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.show_famulei_loading(true)
    // *********************************  刷新产品信息
    var app_data = getApp().globalData;
    //-----1. 清空本地产品数据
    try {
      app_data.productInfo = null
      app_data.optionsInfo = null
    } catch (e) {}
    //-----2. 从数据库重新获取产品数据
    // setTimeout(function () {
    wx.cloud.callFunction({
        name: 'getData'
      })
      .then(function (res) {
        //将读取的产品信息数据，赋值给全局变量
        // console.log("productInfo:",res.result.productInfo)
        // console.log("optionsInfo:", res.result.optionsInfo)
        app_data.productInfo = res.result.productInfo
        app_data.optionsInfo = res.result.optionsInfo

        // 等待产品数据加载完成后，更新购物车中产品信息
        try {
          that.updateCartListProductsPrice()
          that.freshBuyCountAndallPrice();
        } catch (e) {
          console.log("刷新购物车信息错误，已自动清空")
          that.clearCartClick()
        }
      })
      .catch(function (res) {
        this.show_famulei_loading(false)
        wx.showModal({
          title: '加载失败',
          content: '请检查您的网络',
          showCancel: false,
        })
      })
    // }, 4000, app_data)
    // ********************************* 定时器 检测产品数据是否获取完成
    let time = 0
    let check_clock = setInterval(() => {
      time = time + 100
      console.log("计时器:" + time + "ms")
      if (app_data.productInfo !== null) {
        this.show_famulei_loading(false)
        // 根据productData获取优惠产品详情列表
        var promotionList = that.getPromotionList(app_data.productInfo);
        // 
        that.setData({
          yoghourt: app_data.productInfo,
          promotionList: promotionList,
        })
        //*********************************
        //获取每个产品类别模块的高度
        this.getHeight();
        //*********************************关闭计时器
        clearInterval(check_clock)
      } else if (time > 5000) {
        this.show_famulei_loading(false)
        clearInterval(check_clock)
        wx.showModal({
          title: '网络故障',
          content: '无法加载产品数据，请检查您的网络',
          showCancel: false,
          confirmText: '我知道了',
          complete: function (res) {
            if (res.confirm) {
              wx.navigateBack()
            }
          }
        })
      }
    }, 100, check_clock, time)
  },
  //-----------------------------------------------------------------检测购物车中产品价格有没有更新
  updateCartListProductsPrice: function () {
    //*************** 1.每次显示时，同步购物车信息
    let cartList = wx.getStorageSync('cartList')
    if (cartList == "" || cartList.length == 0) {
      console.log("---购物车为空，无需执行信息刷新---")
      this.setData({
        cartListData: [] //购物车列表数据
      })
      return
    }
    //*************** 2.遍历购物车 进行信息刷新
    for (let n = cartList.length - 1; n >= 0; n--) {
      let yoghourt = cartList[n]
      // 获取产品最新信息
      let product_info = this.get_cartlist_youhourt_info(yoghourt)
      // console.log("购物车("+ n +")",product_info)
      if (product_info === 0) {
        cartList.splice(n, 1)
        // console.log("删除某项后：", cartList)
      } else {
        cartList[n] = product_info
      }
    }
    console.log(cartList)
    // 同步到当前页面中
    this.setData({
      cartListData: cartList,
    })
  },

  // 传入购物车一行产品信息：返回---> 更新后的信息 / 0 说明产品已下架
  get_cartlist_youhourt_info: function (yoghourt) {

    // 查找产品信息 参数：id，typeid
    let id = Number(yoghourt.id)
    let typeid = Number(yoghourt.typeid)
    // 查找小料信息 参数：optiontypeid，options
    let optiontypeid = Number(yoghourt.optiontypeid)
    let additions = yoghourt.additions

    let productInfo = getApp().globalData.productInfo

    //--------------------------------
    // 定义返回信息：0
    let exist = false
    // 查找 typeid 对应的产品列表
    let one_type_yoghourts = []
    for (let i = 0; i < productInfo.length; i++) {
      if (Number(productInfo[i].id) == typeid) {
        one_type_yoghourts = productInfo[i].yoghourt
        break
      }
    }
    // 查找 id 对应的产品
    for (let n = 0; n < one_type_yoghourts.length; n++) {
      let new_yoghourt = one_type_yoghourts[n]
      if (Number(new_yoghourt.id == id && Number(new_yoghourt.visible) == 1)) {

        exist = true

        // 如果找到了，对 yoghourt 进行修改     时宝顺
        let count = Number(yoghourt.count)
        let new_promotionprice = Number(new_yoghourt.promotionprice)
        let new_price = Number(new_yoghourt.price)
        // 酸奶裸价(不含小料的单个价格)
        yoghourt.nakedPrice = new_promotionprice > 0 ? new_promotionprice : new_price
        // 酸奶折扣(酸奶价格 - 促销价) * 数量
        yoghourt.discount = new_promotionprice > 0 ? (new_price - new_promotionprice) * count : 0
        // [如果有加料信息]--->刷新加料信息
        //--------如果发现加料信息下架则删除购物篮整行
        if (additions.length > 0) {
          yoghourt.additions = this.get_yoghourt_additions(optiontypeid, additions)
          if (yoghourt.additions == 0) {
            return 0
          }
        }
        // 单行产品栏总价
        let additions_total_price = 0
        for (let j = 0; j < yoghourt.additions.length; j++) {
          additions_total_price += yoghourt.additions[j].addPrice
        }
        yoghourt.price = (yoghourt.nakedPrice + additions_total_price) * count
        break
      }
    }
    // 判断是否找到
    if (exist) {
      // console.log(yoghourt)
      return yoghourt
    } else {
      return 0
    }
  },
  // 根据 选项id 和 加料名称 查找加料信息  返回值：0-->有小料下架 additions:否则返回一个arr对象
  get_yoghourt_additions: function (optiontypeid, additions) {

    // 获取选项信息
    let optionsInfo = getApp().globalData.optionsInfo

    // 确定小料的查找类型：optiontypeid:'1,5,7' [逗号分隔开的string]
    let optiontypeidArr = (optiontypeid + '').split(',')

    // 遍历数据 optionsInfo 最外层
    let all_options_list = []
    for (let n1 = 0; n1 < optionsInfo.length; n1++) {
      let optiontypeid = String(optionsInfo[n1].id)
      if (optiontypeidArr.indexOf(optiontypeid) > -1) {
        // 如果找到执行的 optiontypeid 则进行遍历[optionData]
        let son_optionsInfo = optionsInfo[n1].optionData
        for (let n2 = 0; n2 < son_optionsInfo.length; n2++) {
          // 对 optionData 中的 [optionlistData] 进行遍历
          let optionlistData = son_optionsInfo[n2].optionlistData
          for (let n3 = 0; n3 < optionlistData.length; n3++) {
            all_options_list.push(optionlistData[n3])
          }
        }
      }
    }
    // console.log("所有涉及类别小料汇总：", all_options_list)


    // 在小料列表汇总中更新小料价格
    for (let n1 = additions.length - 1; n1 >= 0; n1--) {
      // 加料名称
      let addName = additions[n1].addName

      let exist = false
      for (let n2 = 0; n2 < all_options_list.length; n2++) {
        if (all_options_list[n2].name == addName) {
          // console.log(addName + "==" + all_options_list[n2].name)
          exist = true
          additions[n1].addPrice = Number(all_options_list[n2].price)
          break
        }
      }
      // 如果未找到同名的小料
      if (!exist) {
        // console.log("小料[" + n1 + '.' +addName + "]已下架")
        additions.splice(n1, 1)
        return 0
      }
    }
    // console.log(additions)
    return additions
  },
  //-----------------------------------------------------------------
  //----------------------------------------刷新判断是否在标准收费时间段
  checkWhetherPayExtraDeliveryCost: function () {
    // 仅在[外卖配送]前提下执行
    if (this.data.order.typeId !== 3) {
      return
    }
    // 判断当前时间是否在 骑手工作 [时间段]
    let settings = this.data.settings
    let inOpenTimeSpan = util.timeRange(settings.normalTimeStart, settings.normalTimeEnd)
    // 如果在正常时间段
    if (inOpenTimeSpan) {
      this.setData({
        extraDeliveryCost: 0
      })
    } else { // 超出骑手工作时间段
      this.setData({
        extraDeliveryCost: Number(settings.extraDeliveryCost)
      })
    }
  },
  //----------------------------------------显示/隐藏 Loading图标
  show_famulei_loading: function (bool) {
    this.setData({
      showLoading: bool
    })
  },
  //----------------------------------------获取特价产品列表
  getPromotionList: function (productData) {
    let promotionList = [];
    //根据productInfo获取有特价优惠的产品
    for (let i = 0; i < productData.length; i++) {
      let oneClass = productData[i].yoghourt
      for (let n = 0; n < oneClass.length; n++) {
        let oneYoghourt = oneClass[n]
        if (Number(oneYoghourt.promotionprice) != 0) //说明有促销价
        {
          promotionList.push(oneYoghourt.name + '-特价' + Number(oneYoghourt.promotionprice).toFixed(1) + '元起')
        }
      }
    }

    return promotionList;

  },
  //---------------------------------导航栏点击事件
  navClick: function (e) {
    var temp = e.currentTarget.dataset.id;
    this.setData({
      scrollId: 'navType' + temp,
      navActiveId: temp
    })
  },
  //---------------------------------滚动栏滚动时，触发事件
  onScroll: function (e) {
    //console.log('触发了滚动事件')
    // 用户每滚动 300 的距离，去触发一次定位
    var deltaY = e.detail.deltaY
    scrolldistance = scrolldistance + Math.abs(deltaY)
    // console.log(scrolldistance)
    if (scrolldistance < 300) {
      return
    } else {
      scrolldistance = 0
    }
    var scrollTop = e.detail.scrollTop;
    var navActiveId = 0;
    for (var i = 0; i < heightArr2.length; i++) {
      if (scrollTop >= 0 && scrollTop < heightArr2[0]) {
        navActiveId = 0
      } else if (scrollTop >= heightArr2[i] && scrollTop < heightArr2[i + 1]) {
        navActiveId = i + 1
      }
    }
    // 仅当导航栏id改变时，再去修改 navActiveId的值
    let old_navActiveId = this.data.navActiveId
    if (navActiveId !== old_navActiveId) {
      this.setData({
        navActiveId: navActiveId
      })
    }
  },
  //---------------------------------打开商品展示详情
  openDetail: function (e) {
    var info = e.currentTarget.dataset.info
    this.setData({
      detailInfo: info,
      showDetail: true

    })
  },
  //---------------------------------打开商品详情图片
  previewImageClick: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.image, // 当前显示图片的http链接
      urls: [e.currentTarget.dataset.image] // 需要预览的图片http链接列表
    })
  },
  //---------------------------------关闭商品展示详情
  closeDetail: function (e) {
    this.setData({
      showDetail: false,
      detailInfo: ''
    })
  },
  consoleLogHello: function () {
    console.log('hello!');
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //------------------------------------获取产品列表中的四个模块的高度，组成一个数组
  getHeight: function () {
    var that = this;
    var heightArr = [];
    var s = 0;
    var yoghourt = this.data.yoghourt;
    for (var i = 0; i < yoghourt.length; i++) {
      var query = wx.createSelectorQuery();
      var idSelector = '#navType' + i;
      query.select(idSelector).boundingClientRect(function (rect) {
        s = s + rect.height // 节点的高度
        heightArr.push(s);
      }).exec()
    }
    //console.log(heightArr)
    getApp().globalData.heightArr = heightArr;
    heightArr2 = heightArr
    console.log(getApp().globalData.heightArr)
  },
  //------------------------------------刷新运费显示
  calculateDeliveryCost: function () {
    // 仅在订单类型为[外卖配送]时刷新运费
    if (this.data.order.typeId !== 3) {
      return
    }
    let deliveryRules = this.data.settings.deliveryRules || [];
    /**
     * baseDeliveryCost: 3
       deliveryDiscount: 0
       enableDeliveryDiscount: false
       enableOrderMinCharge: true
       minCharge: 25
       orderMoneyLimit: 0
       rangeLeft: 0
       rangeRight: 1500
     */
    console.log(this.data.settings.deliveryRules)
    // ----- 计算配送付费（用户进入此界面时，已经确定其距离）
    let distance = Number(this.data.order.addressInfo.distance) // 获取配送距离m
    let order_money = Number(this.data.allPrice) //当前订单金额

    let deliveryTip = "";
    for (let i = 0, len = deliveryRules.length; i < len; i++) {
      let {
        rangeLeft,
        rangeRight,
        baseDeliveryCost,
        enableOrderMinCharge,
        minCharge,
        enableDeliveryDiscount,
        orderMoneyLimit,
        deliveryDiscount
      } = deliveryRules[i];
      if (distance > rangeLeft && distance <= rangeRight) {
        // a. 是否开启最低起送价限制
        let canDelivery = false;
        let canDeliveryNeedBuy;
        if (enableOrderMinCharge) {
          // 如果开启设置，必须满足起送价才能下单，需要校验当前订单价格和设置中的最低要求
          canDelivery = order_money >= minCharge

          // 计算还需购买多少元-->允许配送
          canDeliveryNeedBuy = (minCharge * 100 - order_money * 100) / 100
          canDeliveryNeedBuy = canDeliveryNeedBuy >= 0 ? canDeliveryNeedBuy : 0
          if(canDeliveryNeedBuy > 0){
            deliveryTip = `还差 ${Number(canDeliveryNeedBuy)} 元起送`
          }else{
            deliveryTip = `已满足配送条件`
          }
          
        } else {
          canDelivery = true;
          deliveryTip = `已满足配送条件`
        }

        // b. 是否启用此档区间内的配送优惠
        let deliveryCost = baseDeliveryCost;
        let deliveryCostReduce = 0;
        let needBuyMore = 0;
        if (enableDeliveryDiscount) {
          // 如果开启设置，结合当前订单价格计算优惠后的运费
          deliveryCost = order_money < orderMoneyLimit ? baseDeliveryCost : (baseDeliveryCost * 100 - deliveryDiscount * 100) / 100
          deliveryCost = deliveryCost > 0 ? deliveryCost : 0

          //计算配送费减免值
          deliveryCostReduce = order_money < orderMoneyLimit ? 0 : deliveryDiscount

          // 计算还需购买多少元-->可优惠配送费
          needBuyMore = (orderMoneyLimit * 100 - order_money * 100) / 100
          needBuyMore = needBuyMore >= 0 ? needBuyMore : 0

          // 优先显示起送价信息，因此只有当满足起送价后，才显示还差？元配送费可优惠 X 元
          if(enableOrderMinCharge && canDeliveryNeedBuy === 0){
            if(needBuyMore > 0){
              deliveryTip = `还差 ${needBuyMore} 元配送费可减免 ${deliveryDiscount} 元`
            }else{
              deliveryTip = `配送费已减免 ${Number(deliveryDiscount)} 元`
            }
          }
        }

        // 生成配送费计价说明
        let tipsList = []
        // tipsList.push("满" + orderMoneyLimit + "元减免" + deliveryDiscount + "元")
        // console.log("配送费说明：", tipsList)

        // 同步到页面显示
        this.setData({
          canDelivery: canDelivery,
          deliveryCost: deliveryCost, //配送费实际值
          deliveryCostReduce: deliveryCostReduce, //配送费减免值
          needBuyMore: needBuyMore, // 需要多买多少钱免配送费
          deliveryTip: deliveryTip,
          deliveryCostTips: tipsList //配送费信息说明(已弃用)
        })
        break;
      }
    }
  },
  calculateDeliveryCost_old: function () {
    // 仅在订单类型为[外卖配送]时刷新运费
    if (this.data.order.typeId !== 3) {
      return
    }

    console.log(this.data.settings.deliveryRules)
    // ----- 计算配送付费（用户进入此界面时，已经确定其距离）
    let distance = Number(this.data.order.addressInfo.distance) // 获取配送距离m
    let order_money = Number(this.data.allPrice) //当前订单金额

    // ----- 基础配送费用
    let baseDeliveryCost = 0 // 基础配送费用
    let orderMoneyLimit = 0 // 达到运费满减的订单金额
    let deliveryDiscount = 0 // 达到满减的优惠金额
    if (distance > 0 && distance <= 1000) {
      baseDeliveryCost = 1
      orderMoneyLimit = 10
      deliveryDiscount = 1
    } else if (distance > 1000 && distance <= 2000) {
      baseDeliveryCost = 3
      orderMoneyLimit = 30
      deliveryDiscount = 3
    } else if (distance > 2000 && distance <= 3000) {
      baseDeliveryCost = 4
      orderMoneyLimit = 35
      deliveryDiscount = 4
    } else if (distance > 3000 && distance <= 4500) {
      baseDeliveryCost = 5
      orderMoneyLimit = 45
      deliveryDiscount = 5
    } else {
      baseDeliveryCost = 99
      orderMoneyLimit = 990
      deliveryDiscount = 99
    }
    // 当前配送费(未达到订单优惠金额，按照标准配送费收取，否则)
    let deliveryCost = order_money < orderMoneyLimit ? baseDeliveryCost : (baseDeliveryCost - deliveryDiscount)
    deliveryCost = deliveryCost > 0 ? deliveryCost : 0
    console.log("配送费：", deliveryCost)

    //计算配送费减免值
    let deliveryCostReduce = order_money < orderMoneyLimit ? 0 : deliveryDiscount

    // 计算还需购买多少元-->免配送费
    let needBuyMore = orderMoneyLimit - order_money
    needBuyMore = needBuyMore >= 0 ? needBuyMore : 0

    // 生成配送费计价说明
    let tipsList = []
    tipsList.push("满" + orderMoneyLimit + "元减免" + deliveryDiscount + "元")
    // console.log("配送费说明：", tipsList)

    // 同步到页面显示
    this.setData({
      deliveryCost: deliveryCost, //配送费实际值
      deliveryCostReduce: deliveryCostReduce, //配送费减免值
      needBuyMore: needBuyMore, // 需要多买多少钱免配送费
      deliveryCostTips: tipsList //配送费信息说明
    })
  },
  //------------------------------------刷新运费显示
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    //*************** 1.每次显示时，同步购物车信息
    var cartList = wx.getStorageSync('cartList')
    // console.log("cartList:", cartList)
    if (cartList == "") {
      this.setData({
        cartListData: [] //购物车列表数据
      })
    } else {
      this.setData({
        cartListData: cartList,
      })
    }
    //*************** 2.每次显示时，同步基本订单信息order和店铺设置settings
    this.setData({
      order: getApp().globalData.order, //同步订单类型信息
      settings: getApp().globalData.settings //店铺设置
    })
    //*************** 3.根据存储的购物车信息，刷新购买总数量和购买总价格，同时刷新运费显示
    this.freshBuyCountAndallPrice();

    //*************** 4.判断是否需要收取 附加服务费
    this.checkWhetherPayExtraDeliveryCost()

    // ************** 5. 提示店铺地址变更
    let addressChangeFlag = wx.getStorageSync('addressChangeFlag')
    if(addressChangeFlag && addressChangeFlag === 'done'){
      console.log('已提示此用户店铺地址变更')
    }else{
      wx.showModal({
        title: '友情提示',
        content: '店铺搬至留城路80号（鑫苑社区北门往东第二个门面）',
        showCancel: false,
        confirmText: '我知道了',
        success: res => {
          if(res.confirm){
            wx.setStorageSync('addressChangeFlag', 'done')
          }
        }
      })
    }
  },
  //----------------------------------------隐藏特价商品列表
  hidePromotionForm: function () {
    this.setData({
      showPromotionList: false
    })
  },
  showPromotion: function () {
    this.setData({
      showPromotionList: true
    })
  },
  //***********************************弹出产品选项界面***************************************
  openOption: function (e) {
    var info = e.currentTarget.dataset.info;
    //console.log(info)
    //-------------------------------1.刷新当前产品价格显示
    //获取商品的实际销售价格
    var initialPrice = 0;
    var discount = 0;
    if (info.promotionprice == 0) {
      //(1)所选商品没有优惠价格
      initialPrice = info.price;
    } else {
      //(2)所选商品有优惠价格
      initialPrice = info.promotionprice;
      discount = info.price - info.promotionprice;
    }
    //-------------------------------2.根据当前产品的[加料选项optiontypeid]获取加料数据
    //optiontypeid:'1,5,7' [逗号分隔开的string]

    // ---  标记 let optionsInfo = wx.getStorageSync("optionsInfo") //获取内存中的选项信息
    let optionsInfo = getApp().globalData.optionsInfo
    //console.log(optionsInfo)
    let typeidArr = (info.optiontypeid + '').split(',')
    //console.log(typeidArr)
    let typeid = info.optiontypeid;

    //定义选项集合：由多个id组成
    let optionData = [];
    let optionRemark = '';

    //为提高循环效率，获取数组长度
    let optionsInfoLength = optionsInfo.length
    let typeidArrLength = typeidArr.length

    for (let i = 0; i < optionsInfoLength; i++) {
      for (let n = 0; n < typeidArrLength; n++) {
        if (Number(optionsInfo[i].id) == Number(typeidArr[n])) {
          //(1)将满足的加料选项加入
          let length3 = optionsInfo[i].optionData.length
          for (let m = 0; m < length3; m++) {
            optionData.push(optionsInfo[i].optionData[m])
          }
          //(2)获取加料说明
          if (optionsInfo[i].remark != '') {
            optionRemark = optionRemark + optionsInfo[i].remark + '; \n '
          }
        }
      }
    }

    //-------------------------------3.同步相关数据至视图层
    this.setData({
      showDetail: false, //设置选项窗体可见
      detailInfo: info, //传输产品信息至此窗体
      optionData: optionData, //当前产品选项数据
      optionRemark: optionRemark, //产品选项加料说明
      initialPrice: initialPrice, //选项列表中的价格
      currentPrice: initialPrice, //当前所选产品价格
      currentDiscount: discount, //当前所选产品的折扣价格
      optionDescrib: '', //已选加料说明
      showOption: true, //设置选项窗体可见
      optionFormScrollTop: 0, //选项滚动条回归顶端
      currentAdditions: [] //当前产品附加选项清空
    })
  },
  //***********************************选项标签【点击事件】***************************************
  optionClick: function (e) {

    let dataset = e.currentTarget.dataset //获取e传递的数据集合
    //console.log(dataset)
    let choose = dataset.choose //单选or多选
    let index1 = dataset.index1 //一级index
    let index2 = dataset.index2 //二级index
    let listid = dataset.listid //选项id
    let price = dataset.price //选项加价
    let selected = dataset.selected //选项状态   
    let optionData = this.data.optionData; //当前产品选项集合

    //---------------------------------------------------------1.写入selected属性值
    if (selected == 0) //由未标记---变为已标记 0->1
    {
      //(1)展示此加料：加价
      if (Number(price) > 0) {
        wx.showToast({
          image: '../../images/coin.png',
          title: '+' + Number(price),
          duration: 500
        })
      }
      //(2)同步变更：selectd值
      if (choose == '多选') {
        optionData[index1].optionlistData[index2].selected = 1
      } else {
        //单选时，需要先设置同组selected=0
        let len = optionData[index1].optionlistData.length
        for (let j = 0; j < len; j++) {
          if (j == index2) {
            optionData[index1].optionlistData[j].selected = 1
          } else {
            optionData[index1].optionlistData[j].selected = 0
          }
        }
      }
    } else //由已标记---变为未标记 1->0
    {
      //(1)展示此加料：减价
      if (Number(price) > 0) {
        wx.showToast({
          image: '../../images/coin_sub.png',
          title: '-' + Number(price),
          duration: 400
        })
      }
      //(2)同步变更：selectd值 [无论单选or多选，点击已选标签都是取消选择]
      optionData[index1].optionlistData[index2].selected = 0
    }
    //---------------------------------------------------------2.通过循环获取已选加料、价格
    let label = '';
    let addPrice = 0;
    let additions = []; //定义一个空数组，用来存放小料加价说明
    let initialPrice = Number(this.data.initialPrice);
    let optionDataLength = optionData.length
    for (var i = 0; i < optionDataLength; i++) {
      var temp = optionData[i].optionlistData;
      for (var j = 0; j < temp.length; j++) {
        if (temp[j].selected == 1) //如果选中状态
        {
          label += temp[j].name + '+' //已选说明
          addPrice += Number(temp[j].price) //加料总价
          additions.push({
            "addName": temp[j].name,
            "addPrice": Number(temp[j].price)
          })
        }
      }
    }
    //---------------------------------------------------------3.同步数据显示
    this.setData({
      optionData: optionData,
      currentPrice: initialPrice + addPrice, //选项列表中的价格
      optionDescrib: label.substring(0, label.length - 1), //已选加料说明
      currentAdditions: additions //将当前所选加料记录成列表
    })
  },
  //***********************************【关闭产品可选项】***************************************
  closeOption: function (e) {
    this.setData({
      showOption: false
    })
  },
  //***********************************【我选好了】点击事件***************************************
  AlreadySelectClick: function (e) {

    //增加校验:对当前的optionData循环，当有单选类别时必选[否则：提醒+退出]
    let optionData = this.data.optionData
    let optionDataLen = optionData.length
    for (let i = 0; i < optionDataLen; i++) {
      if (optionData[i].choose == '单选') {
        let optionlistData = optionData[i].optionlistData
        let optionlistDataLen = optionlistData.length
        let selectSum = 0
        for (let j = 0; j < optionlistDataLen; j++) {
          selectSum += Number(optionlistData[j].selected)
        }
        if (selectSum == 0) { //为0说明：单选框没有选择
          wx.showToast({
            title: optionData[i].type + '尚未选择',
            icon: 'none'
          })
          return;
        }
      }
    }
    //-------------------------------------校验无误：继续运行以下添加至购物车操作
    let cartListData = this.data.cartListData; //获取此时的购物车信息
    let id = this.data.detailInfo.id; //获取当前 商品id
    let typeid = this.data.detailInfo.typeid //获取当前 产品类别id
    let optiontypeid = this.data.detailInfo.optiontypeid //获取当前 选项类别id
    let name = this.data.detailInfo.name; //获取当前 商品名称
    let options = this.data.optionDescrib; //获取当前所选加料描述
    let nakedPrice = this.data.initialPrice; //获取当前所选产品的裸价(不加任何小料)
    let price = this.data.currentPrice; //当前所选产品(含小料)的总价
    let addtions = this.data.currentAdditions; //当前所选小料的名称价格列表
    let discount = this.data.currentDiscount; //当前所选产品的折扣价格
    let haveSame = false; //标识符：是否有相同的产品

    //通过遍历循环购物车数据数组，判断当前购物车中是否已经有此产品

    for (var i = 0; i < cartListData.length; i++) {
      if (cartListData[i].key == name + '(' + options + ')') //判断是否能按照key值找到相同产品
      {
        let danjia = Number(cartListData[i].price) / Number(cartListData[i].count); //获取单价
        let zhekou = Number(cartListData[i].discount) / Number(cartListData[i].count); //获取单件折扣
        cartListData[i].count += 1;
        cartListData[i].price = Number(cartListData[i].count) * danjia;
        cartListData[i].discount = Number(cartListData[i].count) * zhekou;
        haveSame = true;
        break;
      }
    }
    if (haveSame == false) //如果没有相等的产品，说明要把当前产品信息，添加至购物车数组中
    {
      var newProduct = {};
      newProduct.id = id;
      newProduct.typeid = typeid;
      newProduct.optiontypeid = optiontypeid;
      newProduct.key = name + '(' + options + ')';
      newProduct.name = name;
      newProduct.options = options;
      newProduct.nakedPrice = nakedPrice;
      newProduct.price = Number(price);
      newProduct.discount = discount;
      newProduct.count = 1;
      newProduct.additions = addtions;
      newProduct.folded = true; //用来标识加料详情是否展开
      cartListData.push(newProduct);
    }

    this.setData({
      cartListData: cartListData,
      showOption: false
    })
    this.freshBuyCountAndallPrice();
  },
  //--------------------------------------------购物车中 点击加料标签时候，弹窗提示
  addtionsLabelClick: function (e) {
    let content = e.currentTarget.dataset.content;
    let name = e.currentTarget.dataset.name;
    wx.showModal({
      title: '友情提示',
      content: '如果您需要删除或增加部分小料，请删除后重新添加至购物车噢~',
      showCancel: false,
      confirmText: '我知道了'
    })
  },
  //--------------------------------------------刷新购物车 总数量及价格
  freshBuyCountAndallPrice: function () {

    var cartListData = this.data.cartListData;
    var buyCount = 0;
    var allPrice = 0;
    var allDiscount = 0;

    for (var i = 0; i < cartListData.length; i++) {
      buyCount += Number(cartListData[i].count)
      allPrice += Number(cartListData[i].price)
      allDiscount += Number(cartListData[i].discount)
    }
    this.setData({
      buyCount: buyCount,
      allPrice: allPrice,
      allDiscount: allDiscount
    })

    //*************** 每次刷新价格的时候，刷新运费显示
    this.calculateDeliveryCost()
  },
  //------------------------------------------清空购物车
  clearCartClick: function (e) {
    this.setData({
      cartListData: [],
      buyCount: 0,
      allPrice: 0,
      allDiscount: 0,
      showCartInfo: false
    })
    this.calculateDeliveryCost()
  },
  //------------------------------------------购物车中减少单品数量
  subCountClick: function (e) {
    var key = e.currentTarget.dataset.key
    var cartListData = this.data.cartListData
    var length = cartListData.length
    for (var n = 0; n < length; n++) {
      if (cartListData[n].key == key) //找到正在调整的数组对象
      {
        var count = Number(cartListData[n].count)
        var price = Number(cartListData[n].price) / count
        var discount = Number(cartListData[n].discount) / count
        if (count == 1) {
          cartListData.splice(n, 1) //在数组中删除此项
        } else {
          cartListData[n].count = count - 1;
          cartListData[n].price = price * (count - 1);
          cartListData[n].discount = discount * (count - 1);
        }
        break;
      }
    }
    this.setData({
      cartListData: cartListData
    })
    this.freshBuyCountAndallPrice();
  },
  //------------------------------------------购物车中增加单品数量
  addCountClick: function (e) {

    var key = e.currentTarget.dataset.key;
    var cartListData = this.data.cartListData;

    for (var i = 0; i < cartListData.length; i++) {
      if (cartListData[i].key == key) {
        var count = Number(cartListData[i].count)
        var price = Number(cartListData[i].price) / count
        var discount = Number(cartListData[i].discount) / count
        cartListData[i].count = count + 1;
        cartListData[i].price = price * (count + 1);
        cartListData[i].discount = discount * (count + 1);
        break;
      }
    }
    this.setData({
      cartListData: cartListData
    })

    this.freshBuyCountAndallPrice();
  },
  //--------------------------------------------关闭购物车信息
  hideCartForm: function (e) {
    this.setData({
      showCartInfo: false
    })
  },
  //--------------------------------------------打开购物车信息
  openCartForm: function (e) {

    var buyCount = this.data.buyCount;

    //判断购物车是否有信息
    if (buyCount == 0) {
      wx.showToast({
        title: '车车空空如也~',
        image: '../../images/sorry-yellow.png',
        duration: 1000
      })
      return;
    }

    //判断当前购物车是打开状态，还是关闭状态

    var showCartInfo = this.data.showCartInfo;
    this.setData({
      showCartInfo: !showCartInfo
    })
  },

  //------------------------------------记录购物车信息至内存
  recordCardListData: function () {
    this.setData({
      showCartInfo: false
    })
    //每次离开页面，将购物车中的信息记录至内存
    wx.setStorageSync('cartList', this.data.cartListData)
  },

  //------------------------------------跳转至【订单确认】页面
  goToConfirmPage: function () {
    //避免连击
    this.data.clickTimes += 1
    console.log("去结算点击次数:", this.data.clickTimes)
    if (this.data.clickTimes > 1) {
      return
    }
    let that = this
    that.show_famulei_loading(true)
    //订单确认前：再次查询店铺设置
    util.queryShopSettings().then(res => {
      let settings = res.data
      that.setData({
        settings: settings
      })
      //获取店铺营业状态
      let inOpenTimeSpan = util.timeRange(settings.openTime, settings.closeTime)
      let shopState = settings.shopState
      that.show_famulei_loading(false)
      if (inOpenTimeSpan && shopState == '正常营业') {
        that.data.clickTimes = 0 //恢复[去结算]点击次数
        let typeId = getApp().globalData.order.typeId
        console.log("typeId:", typeId)
        //正常营业状态下，检测就餐方式是否为【开启状态】
        if (settings.reserve == '关闭预约' && typeId == 2) {
          wx.showModal({
            title: '店家临时关闭预约功能',
            content: '非常抱歉,请至首页重新选择其他就餐方式',
            showCancel: false,
            complete: function () {
              wx.navigateBack({
                delta: 1
              })
            }
          })
          return;
        } else if (settings.deliver == '关闭外卖' && typeId == 3) {
          wx.showModal({
            title: '店家临时关闭外卖功能',
            content: '非常抱歉,请移至首页重新选择其他就餐方式',
            showCancel: false,
            complete: function () {
              wx.navigateBack({
                delta: 1
              })
            }
          })
          return;
        } else //用户选择就餐方式在时间及业务支持范围中
        {
          that.checkWhetherPayExtraDeliveryCost() // 计算附加服务费
          // 若用户外卖，校验用户是否满足配送条件
          if(typeId == 3){
            this.calculateDeliveryCost()
            if(this.data.canDelivery === false){
              wx.showModal({
                title: '未满足配送条件',
                content: `您的订单${this.data.deliveryTip}!`,
                showCancel: false,
                confirmText: '继续选购'
              })
              return;
            }
          }
          if (typeId == 3 && Number(that.data.extraDeliveryCost) > 0) {
            wx.showModal({
              title: '附加服务费',
              content: "当前时间超出正常派送时间（" + settings.normalTimeStart + "-" + settings.normalTimeEnd + "）" + ",需收取附加服务费 " + settings.extraDeliveryCost + " 元",
              confirmText: '我知道了',
              complete: function (res) {
                if (res.confirm) {
                  //跳转至订单确认页面
                  wx.navigateTo({
                    url: '../../pages/confirm/confirm',
                  })
                } else {
                  return
                }
              }
            })
          } else { //可以跳转至订单确认页面了
            wx.navigateTo({
              url: '../../pages/confirm/confirm',
            })
          }
        }
      } else { //店铺已经休息
        that.data.clickTimes = 0 //恢复[去结算]点击次数
        wx.showModal({
          title: '店家已休息',
          content: '非常抱歉,明天再来吧',
          showCancel: false
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

    // 每次离开页面，将购物车中的信息记录至内存
    this.recordCardListData();
    // 同步运费信息至全局变量
    getApp().globalData.deliveryCost = this.data.order.typeId == 3 ? this.data.deliveryCost : 0
    getApp().globalData.extraDeliveryCost = this.data.extraDeliveryCost
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //每次离开页面，将购物车中的信息记录至内存
    this.recordCardListData();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})